package com.caigou.modules.famous.ui.challenge.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.dareTypeName
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.comm.base.widget.TipsDialog
import com.caigou.modules.famous.R
import com.caigou.modules.famous.adpter.MyChallengeItemAdapter
import com.caigou.modules.famous.bean.ChallengeParamsItemBean
import com.caigou.modules.famous.bean.MyChallengeBean
import com.caigou.modules.famous.bean.PublishItemBean
import com.caigou.modules.famous.databinding.FragmentMyChallengeBinding
import com.caigou.modules.famous.ui.challenge.FamousChallengeActivity
import com.caigou.modules.famous.viewmodel.ChallengeViewModel
import com.caigou.modules.famous.widget.JoinChallengeDialog
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/10
 */
@AndroidEntryPoint
class MyChallengeFragment : BaseFragment() {

    private var _binding: FragmentMyChallengeBinding? = null
    private val binding get() = _binding!!

    private val challengeViewModel: ChallengeViewModel by viewModels()

    private var dareTypeId = 0
    private var highestMoneyRule = 100
    private var currentPeriods = 0
    private var clickPos = 0

    private val challengeParamsList = mutableListOf<ChallengeParamsItemBean>()

    private val mAdapter: MyChallengeItemAdapter by lazy {
        MyChallengeItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentMyChallengeBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.myChallengeSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchMyChallengeList()
            }
        }


        binding.myChallengeRecyclerView.run {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            clickPos = position
            when (view.id) {
                R.id.item_my_challenge_btn_cancel -> {
                    val challengeRecordId = mAdapter.getItem(position).id
                    with(TipsDialog(requireActivity(), true)) {
                        tvTitle.visibility = View.GONE
                        tvContent.text = "确认放弃该任务吗？放弃后该任务将终止，且报名费不会退回！但您可以重新挑战该任务"
                        tvLeft.text = "取消"
                        tvLeft.setOnClickListener {
                            dismiss()
                        }
                        tvRight.text = "确认"
                        tvRight.setTextColor(resources.getColor(R.color.caigou_theme_color))
                        tvRight.setOnClickListener {
                            challengeViewModel.cancelChallenge(challengeRecordId)
                            dismiss()
                        }
                        show()
                    }
                }

                R.id.item_my_challenge_btn_publish -> {
                    val item = mAdapter.getItem(position)
                    val type = (requireActivity() as FamousChallengeActivity).famousType
                    val publishItemBean = PublishItemBean(item.id, item.dareTypeId, item.dareTypeName, item.period)
                    when (item.status) {
                        0 -> {
                            if (item.isLock == 1) {
                                ARouter.getInstance().build(RouterPath.Famous.PAGE_PERSONAL)
                                    .withInt(AppConstants.FAMOUS_TYPE, type)
                                    .withString(AppConstants.USER_ID, AppBackgroundInfo.instance.userBean!!.userId)
                                    .navigation()
                            } else {
                                when (item.dareTypeId) {
                                    14, 15, 16, 17, 20, 21, 22, 35 -> {
                                        ARouter.getInstance().build(RouterPath.Famous.PAGE_PUBLISH_DETAIL2)
                                            .withInt(AppConstants.FAMOUS_TYPE, type)
                                            .withInt(AppConstants.FAMOUS_POST_TYPE, 1)
                                            .withObject(AppConstants.FAMOUS_PUBLISH_ITEM_BEAN, publishItemBean)
                                            .navigation()
                                    }
                                    else -> {
                                        ARouter.getInstance().build(RouterPath.Famous.PAGE_PUBLISH_DETAIL)
                                            .withInt(AppConstants.FAMOUS_TYPE, type)
                                            .withInt(AppConstants.FAMOUS_POST_TYPE, 1)
                                            .withObject(AppConstants.FAMOUS_PUBLISH_ITEM_BEAN, publishItemBean)
                                            .navigation()
                                    }
                                }
                            }
                        }
                        2 -> {
                            if (challengeParamsList.isNullOrEmpty()) {
                                return@setOnItemChildClickListener
                            }
                            with(JoinChallengeDialog(requireActivity(), dareTypeId, challengeParamsList)) {
                                btnJoin.setOnClickListener {
                                    val successDesc = currentSuccessDesc()
                                    val moneyId = currentMoneyId()
                                    challengeViewModel.joinChallenge(dareTypeId, type, successDesc, moneyId, AppBackgroundInfo.instance.userBean!!.userId)
                                    dismiss()
                                }
                                show()
                            }
                        }
                    }
                }
            }
        }

        binding.myChallengeLayoutSelector.challengeTypeSelectorRgSelector.setOnCheckedChangeListener { group, checkedId ->
            dareTypeId = when (checkedId) {
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnAll.id -> 0
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnSanXiao.id -> 11
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnLiuXiao.id -> 12
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnJiuXiao.id -> 13
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtn5ma.id -> 14
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtn10ma.id -> 15
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtn20ma.id -> 16
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtn35ma.id -> 17
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnPingTeYiXiao.id -> 18
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnPingTeYiWei.id -> 19
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnWuBuZhong.id -> 20
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnQiBuZhong.id -> 21
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnSanZhongYi.id -> 22
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnErLianXiao.id -> 23
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnErLianWei.id -> 24
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnDanShuang.id -> 25
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnDaXiao.id -> 26
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnJiaYe.id -> 27
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShuangBo.id -> 28
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnHeDanShuang.id -> 29
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnSanTou.id -> 30
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnLiuWei.id -> 31
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnSanHang.id -> 32
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnQiWei.id -> 33
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaYiXiao.id -> 34
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnSha5ma.id -> 35
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaYiTou.id -> 36
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaYiWei.id -> 37
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaYiDuan.id -> 38
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaYiHang.id -> 39
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaErWei.id -> 40
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaErXiao.id -> 41
                binding.myChallengeLayoutSelector.challengeTypeSelectorBtnShaBanBo.id -> 42
                else -> 0
            }
            binding.myChallengeCvHeader.visibility = if (dareTypeId == 0) {
                View.GONE
            } else {
                View.VISIBLE
            }
            fetchMyChallengeList()
            fetchChallengeParamsList()
            handleHeaderCardViewUI()
        }

        binding.myChallengeCvHeader.visibility = if (dareTypeId == 0) {
            View.GONE
        } else {
            View.VISIBLE
        }
        binding.myChallengeBtnJoin.setOnClickListener {
            if (challengeParamsList.isNullOrEmpty()) {
                return@setOnClickListener
            }
            with(JoinChallengeDialog(requireActivity(), dareTypeId, challengeParamsList)) {
                btnJoin.setOnClickListener {
                    val successDesc = currentSuccessDesc()
                    val moneyId = currentMoneyId()
                    val type = (requireActivity() as FamousChallengeActivity).famousType
                    challengeViewModel.joinChallenge(dareTypeId, type, successDesc, moneyId, AppBackgroundInfo.instance.userBean!!.userId)
                    dismiss()
                }
                show()
            }
        }

        LiveDataBus.get().with(BusKey.SUBSCRIBE_TYPE_CHANGE, Int::class.java).observe(this) {
            fetchMyChallengeList()
        }

        LiveDataBus.get().with(BusKey.CHALLENGE_PUBLISH_FINISH, Any::class.java).observe(this) {
            fetchMyChallengeList()
        }
    }

    override fun lazyLoad() {
        fetchMyChallengeList()
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(challengeViewModel.myChallengeListLiveData, ::handleGetMyChallengeList)
        observe(challengeViewModel.challengeParamsLiveData, ::handleGetChallengeParamsList)
        observe(challengeViewModel.joinChallengeLiveData, ::handleJoinChallenge)
        observe(challengeViewModel.cancelChallengeLiveData, ::handleCancelChallenge)
    }

    private fun handleGetMyChallengeList(result: Resource<MyChallengeBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取我的挑战信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                mAdapter.setList(result.data!!.list)
                highestMoneyRule = result.data!!.highestMoneyRule
                currentPeriods = result.data!!.currentPeriods
            }
        }
    }

    private fun handleGetChallengeParamsList(result: Resource<MutableList<ChallengeParamsItemBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取挑战参数信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                challengeParamsList.clear()
                challengeParamsList.addAll(result.data!!)
            }
        }
    }

    private fun handleJoinChallenge(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("参加挑战异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                fetchMyChallengeList()
                showToast(result.data!!)
            }
        }
    }

    private fun handleCancelChallenge(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("放弃挑战异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.myChallengeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                fetchMyChallengeList()
                showToast(result.data!!)
            }
        }
    }

    private fun handleHeaderCardViewUI() {
        binding.myChallengeTvType.text = "类型：${dareTypeName(dareTypeId)}"
        binding.myChallengeTvPeriod.text = "起始期数：${currentPeriods}期"
        binding.myChallengeIvMoney.text = "${highestMoneyRule}元"
    }

    private fun fetchMyChallengeList() {
        val type = (requireActivity() as FamousChallengeActivity).famousType
        challengeViewModel.getMyChallengeList(dareTypeId, type, AppBackgroundInfo.instance.userBean!!.userId)
    }

    private fun fetchChallengeParamsList() {
        if (dareTypeId == 0) {
            return
        }
        challengeViewModel.getChallengeParamsList(dareTypeId)
    }
}